/**
 * @Author: HaoyangDu
 * @Email: HaoyangDu@wits.com
 * @Date: 2024-03-25 16:09:53
 * @LastEditTime: 2024-04-22 15:30:11
 * @LastEditors: your name
 * @Description:
 * @FilePath: \hfxed\src\utils\utils.js
 */

import config from "./config.js";
import { sm2 } from "sm-crypto";

/**
 * @description: 按千位逗号分割
 * @param {*} s 需要格式化的数值
 * @param {*} type 判断格式化后是否需要小数位
 * @return {*} 返回格式化后的数值字符串
 */
export const formatNumber = (s, type = 0) => {
  if (/[^0-9\.]/.test(s)) return "0";
  if (s == null || s == "") return "0";
  s = s.toString().replace(/^(\d*)$/, "$1.");
  s = (s + "00").replace(/(\d*\.\d\d)\d*/, "$1");
  s = s.replace(".", ",");
  var re = /(\d)(\d{3},)/;
  while (re.test(s)) s = s.replace(re, "$1,$2");
  s = s.replace(/,(\d\d)$/, ".$1");
  if (type == 0) {
    // 不带小数位(默认是有小数位)
    var a = s.split(".");
    if (a[1] == "00") {
      s = a[0];
    }
  }
  return s;
};

/**
 * @description: sm2加密
 * @param {*} str
 * @return {*}  加密后的params
 */
export const doEncryptSM2 = (str) => {
  // let encryptData = sm2.doEncrypt(str, config.SM2PublicKey)
  // return encryptData
  return str;
};
/**
 * @description: sm2解密
 * @param {*} str
 * @return {*}  解密后的data
 */
export const doDecryptSM2 = (str) => {
  // let decryptData = sm2.doDecrypt(str, config.SM2PrivateKey)
  // return decryptData
  return str;
};

/**
 * @Author: HaoyangDu@wits.com
 * @description: 校验是否为手机号
 * @return {*}
 */
export const checkMobile = (param) => {
  let reg = /^1[3456789]\d{9}$/;
  return reg.test(param);
};

/**
 * @description: 风控位置信息公共方法
 * @param {type}
 * @return:
 * @Date Changed:
 */
export const getLocation = () => {
  return new Promise((resolve, reject) => {
    getGps()
      .then((res) => {
        getAddress(res.latitude, res.longitude)
          .then((data) => {
            resolve(data);
          })
          .catch((err) => reject(err));
      })
      .catch((err) => reject(err));
  });
};
/**
 * @description: 利用微信定位获取gps坐标
 * @param {type}
 * @return:
 * @Date Changed:
 */
export const getGps = () => {
  return new Promise((resolve, reject) => {
    wx.getLocation({
      type: "wgs84",
      success: (res) => {
        resolve(res);
      },
      fail: (err) => {
        reject(err);
      },
    });
  });
};
/**
 * @description: 微信api获取的坐标通过sdk转腾讯地址
 * @param {type}
 * @return:
 * @Date Changed:
 */
// 引入SDK核心类
import { QQMapWX } from "../lib/qqmap-wx-jssdk.js";
// 实例化API核心类
const qqmapsdk = new QQMapWX({
  key: config.mapKey, // 必填
});
function getAddress(latitude, longitude) {
  return new Promise((resolve, reject) => {
    qqmapsdk.reverseGeocoder({
      location: {
        latitude,
        longitude,
      },
      success: (res) => {
        resolve(res.result.formatted_addresses.standard_address);
      },
      fail: (err) => {
        reject(err);
      },
    });
  });
}
/**
 * @Author: HaoyangDu@wits.com
 * @description:
 * @param {*} latitude
 * @param {*} longitude
 * @return {*}
 */
export const getRange = (to, from) => {
  return new Promise((resolve, reject) => {
    qqmapsdk.calculateDistance({
      mode: "straight",
      from,
      to,
      success: (res) => {
        resolve(res.result.elements[0].distance);
      },
      fail: (err) => {
        console.log(err);
        reject(err);
      },
    });
  });
};
/**
 * @description: 获取当天 YY-MM-DD
 * @param {type}
 * @return:
 */
export const getNowFormatDate = () => {
  let t = new Date();
  let a = "-";
  let e = t.getFullYear();
  let i = t.getMonth() + 1;
  let s = t.getDate();
  if (i >= 1 && i <= 9) {
    i = "0" + i;
  }
  if (s >= 0 && s <= 9) {
    s = "0" + s;
  }
  let n = e + a + i + a + s;
  return n;
};

/**
 * @Author: HaoyangDu@wits.com
 * @description: 获取用户ip地址
 * @return {*}
 */
// export const getIp = () => {
//   return new Promise((resolve, reject) => {
//     wx.request({
//       url: "http://ip-api.com/json",
//       success: (e) => {
//         console.log("ip: ", e.data.query);
//         resolve(e.data.query);
//       },
//       fail: (err) => {
//         console.error("获取IP地址失败：", err);
//         reject(err);
//       },
//     });
//   });
// };

export const getIp = () => {
  // 获取IP地址
  return new Promise((resolve, reject) => {
    wx.getLocalIPAddress({
      success(res) {
        const localip = res.localip;
        console.log(localip);
        resolve(localip);
      },
      fail: (err) => {
        reject(err);
      },
    });
  });
};

/**
 * @Author: HaoyangDu@wits.com
 * @description: 将base64转成临时路径
 * @param {*} dataURL
 * @return {*}
 */
export const base64ToPath = (dataURL) => {
  return new Promise((resolve, reject) => {
    const data = dataURL.replace(/^data:image\/\w+;base64,/, "");
    const filePath = `${wx.env.USER_DATA_PATH}/${Math.random()
      .toString(32)
      .slice(2)}.pdf`;
    wx.getFileSystemManager().writeFile({
      filePath,
      data,
      encoding: "base64",
      success: (res) => {
        console.log("res", res);
        console.log("filePath", filePath);
        resolve(filePath);
      },
      fail: reject,
    });
  });
};
// 分割详情地址
export const cutAdress = function (data = "") {
  // 用正则表达式分割详情地址
  var regex =
    "(?<province>[^省]+省|[^自治区]+自治区|.+市)(?<city>[^自治州]+自治州|.+区划|[^市]+市|.+区)?(?<county>[^市]+市|[^县]+县|[^旗]+旗|.+区)?(?<town>[^区]+区|.+镇)?(?<village>.*)";
  var address = data;
  var result = address.match(regex);
  console.log("result", result);
  return result;
};
